<?php
final class Cart {
  	public function __construct($registry) {
		$this->config = $registry->get('config');
		$this->customer = $registry->get('customer');
		$this->session = $registry->get('session');
		$this->db = $registry->get('db');
		$this->tax = $registry->get('tax');
		$this->weight = $registry->get('weight');

		if (!isset($this->session->data['cart']) || !is_array($this->session->data['cart'])) {
      		$this->session->data['cart'] = array();
    	}
	}
	      
	public function getFoods() {
		$food_data = array();
		
    	foreach ($this->session->data['cart'] as $key => $quantity) {
      		$food = explode(':', $key);
      		$food_id = $food[0];
			$stock = true;

			// Options
      		if (isset($food[1])) {
        		$options = unserialize(base64_decode($food[1]));
      		} else {
        		$options = array();
      		} 
			
      		$food_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "food f LEFT JOIN " . DB_PREFIX . "food_description fd ON (f.food_id = fd.food_id) WHERE f.food_id = '" . (int)$food_id . "' AND fd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND f.date_available <= NOW() AND f.status = '1'");
      	  	
			if ($food_query->num_rows) {
      			$option_price = 0;
				$option_points = 0;
				$option_weight = 0;

      			$option_data = array();
      
      			foreach ($options as $food_option_id => $option_value) {
					$option_query = $this->db->query("SELECT fo.food_option_id, fo.option_id, od.name, o.type FROM " . DB_PREFIX . "food_option fo LEFT JOIN `" . DB_PREFIX . "option` o ON (fo.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE fo.food_option_id = '" . (int)$food_option_id . "' AND fo.food_id = '" . (int)$food_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "'");
					
					if ($option_query->num_rows) {
						if ($option_query->row['type'] == 'select' || $option_query->row['type'] == 'radio' || $option_query->row['type'] == 'image') {
							$option_value_query = $this->db->query("SELECT fov.option_value_id, ovd.name, fov.price, fov.price_prefix FROM " . DB_PREFIX . "food_option_value fov LEFT JOIN " . DB_PREFIX . "option_value ov ON (fov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE fov.food_option_value_id = '" . (int)$option_value . "' AND fov.food_option_id = '" . (int)$food_option_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
							
							if ($option_value_query->num_rows) {
								if ($option_value_query->row['price_prefix'] == '+') {
									$option_price += $option_value_query->row['price'];
								} elseif ($option_value_query->row['price_prefix'] == '-') {
									$option_price -= $option_value_query->row['price'];
								}
								
								$option_data[] = array(
									'food_option_id'       => $food_option_id,
									'food_option_value_id' => $option_value,
									'option_id'               => $option_query->row['option_id'],
									'option_value_id'         => $option_value_query->row['option_value_id'],
									'name'                    => $option_query->row['name'],
									'option_value'            => $option_value_query->row['name'],
									'type'                    => $option_query->row['type'],
									'price'                   => $option_value_query->row['price'],
									'price_prefix'            => $option_value_query->row['price_prefix']
								);								
							}
						} elseif ($option_query->row['type'] == 'checkbox' && is_array($option_value)) {
							foreach ($option_value as $food_option_value_id) {
								$option_value_query = $this->db->query("SELECT fov.option_value_id, ovd.name, fov.price, fov.price_prefix FROM " . DB_PREFIX . "food_option_value fov LEFT JOIN " . DB_PREFIX . "option_value ov ON (fov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE fov.food_option_value_id = '" . (int)$food_option_value_id . "' AND fov.food_option_id = '" . (int)$food_option_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
								
								if ($option_value_query->num_rows) {
									if ($option_value_query->row['price_prefix'] == '+') {
										$option_price += $option_value_query->row['price'];
									} elseif ($option_value_query->row['price_prefix'] == '-') {
										$option_price -= $option_value_query->row['price'];
									}
									
									$option_data[] = array(
										'food_option_id'       => $food_option_id,
										'food_option_value_id' => $food_option_value_id,
										'option_id'               => $option_query->row['option_id'],
										'option_value_id'         => $option_value_query->row['option_value_id'],
										'name'                    => $option_query->row['name'],
										'option_value'            => $option_value_query->row['name'],
										'type'                    => $option_query->row['type'],
										'price'                   => $option_value_query->row['price'],
										'price_prefix'            => $option_value_query->row['price_prefix']
									);								
								}
							}						
						} elseif ($option_query->row['type'] == 'text' || $option_query->row['type'] == 'textarea' || $option_query->row['type'] == 'file' || $option_query->row['type'] == 'date' || $option_query->row['type'] == 'datetime' || $option_query->row['type'] == 'time') {
							$option_data[] = array(
								'food_option_id'       => $food_option_id,
								'food_option_value_id' => '',
								'option_id'               => $option_query->row['option_id'],
								'option_value_id'         => '',
								'name'                    => $option_query->row['name'],
								'option_value'            => $option_value,
								'type'                    => $option_query->row['type'],
								'price'                   => '',
								'price_prefix'            => ''
							);						
						}
					}
      			} 
			
				if ($this->customer->isLogged()) {
					$customer_group_id = $this->customer->getCustomerGroupId();
				} else {
					$customer_group_id = $this->config->get('config_customer_group_id');
				}
				
				$price = $food_query->row['price'];
				
				// food Specials
				$food_special_query = $this->db->query("SELECT price FROM " . DB_PREFIX . "food_special WHERE food_id = '" . (int)$food_id . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY priority ASC, price ASC LIMIT 1");
			
				if ($food_special_query->num_rows) {
					$price = $food_special_query->row['price'];
				}						
				
      			$food_data[$key] = array(
        			'key'             => $key,
        			'food_id'      => $food_query->row['food_id'],
        			'name'            => $food_query->row['name'],
					'shipping'        => $food_query->row['shipping'],
        			'image'           => $food_query->row['image'],
        			'option'          => $option_data,
        			'quantity'        => $quantity,
        			'price'           => ($price + $option_price),
        			'total'           => ($price + $option_price) * $quantity
      			);
			} else {
				$this->remove($key);
			}
    	}
						
		return $food_data;
  	}
		  
  	public function add($menu_id, $qty = 1, $options = array()) {
    	if (!$options) {
      		$key = (int)$menu_id;
    	} else {
      		$key = (int)$menu_id . ':' . base64_encode(serialize($options));
    	}
    	
		if ((int)$qty && ((int)$qty > 0)) {
    		if (!isset($this->session->data['cart'][$key])) {
      			$this->session->data['cart'][$key] = (int)$qty;
    		} else {
      			$this->session->data['cart'][$key] += (int)$qty;
    		}
		}
  	}

  	public function update($key, $qty) {
    	if ((int)$qty && ((int)$qty > 0)) {
      		$this->session->data['cart'][$key] = (int)$qty;
    	} else {
	  		$this->remove($key);
		}
  	}

  	public function remove($key) {
		if (isset($this->session->data['cart'][$key])) {
     		unset($this->session->data['cart'][$key]);
  		}
	}
	
  	public function clear() {
		$this->session->data['cart'] = array();
  	}
	
  	public function getWeight() {
		$weight = 0;
	
    	foreach ($this->getFoods() as $menu) {
			if ($menu['shipping']) {
      			$weight += $this->weight->convert($menu['weight'], $menu['weight_class_id'], $this->config->get('config_weight_class_id'));
			}
		}
	
		return $weight;
	}
	
  	public function getSubTotal() {
		$total = 0;
		
		foreach ($this->getFoods() as $food) {
			$total += $food['total'];
		}

		return $total;
  	}

  	public function getTotal() {
  		$restaurant_id = (int)$this->config->get('config_restaurant_id');
  		$total = 0;
		
		if($restaurant_id){
			foreach ($this->getFoods() as $menu) {
				$total += $menu['total'];
			}
		}else{
			
		}

		return $total;
  	}
  	
	public function getTotalRewardPoints() {
		$total = 0;
		
		$total = ceil($this->getSubTotal() / $this->config->get('config_reward_point_value'));

		return $total;
  	}
  	
  	public function countFoods() {
		$food_total = 0;
			
		$foods = $this->getFoods();
		
		foreach ($foods as $food) {
			$food_total += $food['quantity'];
		}		
					
		return $food_total;
	}
	  
  	public function hasFoods() {
    	return count($this->session->data['cart']);
  	}
  
  	public function hasShipping() {
		$shipping = false;
		
		foreach ($this->getFoods() as $food) {
	  		if ($food['shipping']) {
	    		$shipping = true;
				
				break;
	  		}
		}
		
		return $shipping;
	}
}
?>